package io.terminus.lego.shinda.web.security.service

import io.terminus.lego.shinda.service.service.UserService
import org.apache.commons.logging.LogFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.User
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.stereotype.Component
import java.util.*
import java.util.regex.Pattern

/**
 * spring security默认Form登录加载用户的UserDetailsService
 * @author wangmeng
 * @date 2018/4/16
 */
@Component
class MultityUserDetailsService @Autowired constructor(val userService: UserService) : UserDetailsService {

    val log = LogFactory.getLog(javaClass)
    val pattern = Pattern.compile("^[0-9]+")
    /**
     * 根据form表单的username获取用户详细信息
     */
    override fun loadUserByUsername(username: String?): UserDetails {
        val user: io.terminus.lego.shinda.service.model.User
        if (username!!.contains("@")) {
            user = userService.findUserByEmail(username)!!
        } else if (pattern.matcher(username).matches()) {
            user = userService.findUserByPhone(username)!!
        } else {
            user = userService.findUserByUsername(username)!!
        }

        val dbAuthsSet = HashSet<GrantedAuthority>()

        val dbAuths = ArrayList(dbAuthsSet)

        //返回的是认证后的用户详情，username将成为为authentication.name
        return User(user.username, user.password,
                user.enabled, true, true, true, dbAuths)

    }

}